<template>
  <div class="common-container">
    <el-card class="operation-card">
      <div class="operation-buttons">
        <el-button type="primary" @click="handleAdd">
          <el-icon><Plus /></el-icon> 新增配置
        </el-button>
        <el-select v-model="queryParams.group" placeholder="选择配置组" clearable @change="handleSearch" style="width: 180px; margin-left: 10px;">
          <el-option label="基本配置" value="basic" />
          <el-option label="安全配置" value="security" />
          <el-option label="邮件配置" value="email" />
          <el-option label="存储配置" value="storage" />
          <el-option label="数据库配置" value="database" />
          <el-option label="其他配置" value="other" />
        </el-select>
        <el-input
          v-model="queryParams.keyword"
          placeholder="输入关键字搜索"
          style="width: 200px; margin-left: 10px;"
          clearable
          @keyup.enter="handleSearch"
          @clear="handleSearch"
        >
          <template #suffix>
            <el-icon class="el-input__icon" @click="handleSearch">
              <Search />
            </el-icon>
          </template>
        </el-input>
      </div>
    </el-card>

    <el-card class="table-card">
      <el-table
        v-model:data="tableData"
        :loading="loading"
        border
        stripe
        style="width: 100%"
      >
        <!-- <el-table-column prop="id" label="ID" width="80" /> -->
        <el-table-column prop="config_key" label="配置键名" width="180" />
        <el-table-column prop="config_value" label="配置值" min-width="200" show-overflow-tooltip />
        <el-table-column prop="config_description" label="配置描述" min-width="200" show-overflow-tooltip />
        <el-table-column prop="config_group" label="配置组" width="120">
          <template #default="scope">
            <el-tag :type="getGroupTagType(scope.row.config_group)">
              {{ formatGroupName(scope.row.config_group) }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="created_at" label="创建时间" width="180" />
        <el-table-column label="操作" width="180" fixed="right">
          <template #default="scope">
            <div class="action-container">
              <el-tooltip content="编辑" placement="top">
                <el-button
                  class="action-button"
                  type="primary"
                  circle
                  size="small"
                  @click="handleEdit(scope.row)"
                >
                  <el-icon><Edit /></el-icon>
                </el-button>
              </el-tooltip>
              <el-tooltip content="删除" placement="top">
                <el-button
                  class="action-button"
                  type="danger"
                  circle
                  size="small"
                  @click="handleDelete(scope.row)"
                >
                  <el-icon><Delete /></el-icon>
                </el-button>
              </el-tooltip>
            </div>
          </template>
        </el-table-column>
      </el-table>

      <div class="pagination-container">
        <el-pagination
          v-model:current-page="pagination.currentPage"
          v-model:page-size="pagination.pageSize"
          :total="pagination.total"
          :page-sizes="[10, 20, 30, 50]"
          layout="total, sizes, prev, pager, next, jumper"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </div>
    </el-card>

    <!-- 配置表单对话框 -->
    <el-dialog
      :title="configForm.isAdd ? '新增配置' : '编辑配置'"
      v-model="dialogVisible"
      width="500px"
      destroy-on-close
    >
      <el-form
        ref="configFormRef"
        :model="configForm"
        :rules="configRules"
        label-width="100px"
        style="max-width: 460px"
      >
        <el-form-item label="配置键名" prop="config_key">
          <el-input v-model="configForm.config_key" placeholder="请输入配置键名" :disabled="!configForm.isAdd" />
        </el-form-item>
        <el-form-item label="配置值" prop="config_value">
          <el-input v-model="configForm.config_value" placeholder="请输入配置值" />
        </el-form-item>
        <el-form-item label="配置描述" prop="config_description">
          <el-input
            v-model="configForm.config_description"
            type="textarea"
            :rows="3"
            placeholder="请输入配置描述"
          />
        </el-form-item>
        <el-form-item label="配置组" prop="config_group">
          <el-select v-model="configForm.config_group" placeholder="请选择配置组">
            <el-option label="基本配置" value="basic" />
            <el-option label="安全配置" value="security" />
            <el-option label="邮件配置" value="email" />
            <el-option label="存储配置" value="storage" />
            <el-option label="数据库配置" value="database" />
            <el-option label="其他配置" value="other" />
          </el-select>
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="dialogVisible = false">取消</el-button>
          <el-button type="primary" @click="submitForm">确认</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted } from 'vue'
import {
  Plus,
  Edit,
  Delete,
  Search
} from '@element-plus/icons-vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { getConfigList, createConfig, updateConfig, deleteConfig } from '@/api/system'

// 定义组件名
defineOptions({
  name: 'SystemConfigPage'
})

// 表格数据
const tableData = ref([])
const loading = ref(false)

// 查询参数
const queryParams = reactive({
  group: '',
  keyword: ''
})

// 分页信息
const pagination = reactive({
  currentPage: 1,
  pageSize: 10,
  total: 0
})

// 对话框控制
const dialogVisible = ref(false)
const configFormRef = ref(null)
const configForm = reactive({
  id: '',
  config_key: '',
  config_value: '',
  config_description: '',
  config_group: 'basic',
  isAdd: true
})

// 表单校验规则
const configRules = {
  config_key: [
    { required: true, message: '请输入配置键名', trigger: 'blur' }
  ],
  config_value: [
    { required: true, message: '请输入配置值', trigger: 'blur' }
  ],
  config_group: [
    { required: true, message: '请选择配置组', trigger: 'change' }
  ]
}

// 获取配置列表
const fetchConfigList = async () => {
  loading.value = true
  try {
    const params = {
      ...queryParams
    }
    const res = await getConfigList(params)

    if (res) {
      tableData.value = res
      pagination.total =res.length
    } else {
      tableData.value = []
      pagination.total = 0
    }
  } catch (error) {
    console.error('获取配置列表失败:', error)
    ElMessage.error('获取配置列表失败: ' + (error.message || '未知错误'))
    tableData.value = []
    pagination.total = 0
  } finally {
    loading.value = false
  }
}

// 配置组标签类型
const getGroupTagType = (group) => {
  const groupMap = {
    'basic': 'primary',
    'security': 'danger',
    'email': 'success',
    'storage': 'warning',
    'database': 'info',
    'other': ''
  }
  return groupMap[group] || ''
}

// 格式化配置组名称
const formatGroupName = (group) => {
  const groupMap = {
    'basic': '基本配置',
    'security': '安全配置',
    'email': '邮件配置',
    'storage': '存储配置',
    'database': '数据库配置',
    'other': '其他配置'
  }
  return groupMap[group] || group
}

// 初始化数据
onMounted(() => {
  fetchConfigList()
})

// 搜索
const handleSearch = () => {
  pagination.currentPage = 1
  fetchConfigList()
}

// 分页大小变化
const handleSizeChange = (val) => {
  pagination.pageSize = val
  fetchConfigList()
}

// 当前页变化
const handleCurrentChange = (val) => {
  pagination.currentPage = val
  fetchConfigList()
}

// 新增配置
const handleAdd = () => {
  Object.assign(configForm, {
    id: '',
    config_key: '',
    config_value: '',
    config_description: '',
    config_group: 'basic',
    isAdd: true
  })
  dialogVisible.value = true
}

// 编辑配置
const handleEdit = (row) => {
  Object.assign(configForm, {
    id: row.id,
    config_key: row.config_key,
    config_value: row.config_value,
    config_description: row.config_description || '',
    config_group: row.config_group || 'basic',
    isAdd: false
  })
  dialogVisible.value = true
}

// 删除配置
const handleDelete = (row) => {
  ElMessageBox.confirm(
    `确定要删除配置 "${row.config_key}" 吗？`,
    '警告',
    {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    }
  ).then(async () => {
    try {
      await deleteConfig(row.id)
      ElMessage.success('删除成功')
      fetchConfigList()
    } catch (error) {
      ElMessage.error('删除失败: ' + (error.message || '未知错误'))
    }
  }).catch(() => {
    ElMessage.info('已取消删除')
  })
}

// 提交表单
const submitForm = async () => {
  if (!configFormRef.value) return

  await configFormRef.value.validate(async (valid) => {
    if (valid) {
      try {
        if (configForm.isAdd) {
          // 新增
          await createConfig({
            config_key: configForm.config_key,
            config_value: configForm.config_value,
            config_description: configForm.config_description,
            config_group: configForm.config_group
          })
          ElMessage.success('添加成功')
        } else {
          // 编辑
          await updateConfig(configForm.id, {
            config_value: configForm.config_value,
            config_description: configForm.config_description,
            config_group: configForm.config_group
          })
          ElMessage.success('更新成功')
        }
        dialogVisible.value = false
        fetchConfigList()
      } catch (error) {
        ElMessage.error((configForm.isAdd ? '添加' : '更新') + '失败: ' + (error.message || '未知错误'))
      }
    } else {
      return false
    }
  })
}
</script>

<style scoped>
.common-container {
  padding: 20px;
  height: calc(100vh - 180px);
  display: flex;
  flex-direction: column;
}

.operation-card {
  margin-bottom: 20px;
}

.operation-buttons {
  display: flex;
  align-items: center;
}

.table-card {
  flex: 1;
  display: flex;
  flex-direction: column;
  overflow: hidden;
}

:deep(.el-card__body) {
  height: 100%;
  display: flex;
  flex-direction: column;
}

:deep(.el-table) {
  flex: 1;
  overflow: auto;
}

.pagination-container {
  display: flex;
  justify-content: flex-end;
  margin-top: 16px;
}

.action-container {
  display: flex;
  justify-content: center;
  align-items: center;
  gap: 8px;
}

.action-button {
  font-size: 12px;
  border: none;
  box-shadow: 0 2px 5px rgba(0, 0, 0, 0.1);
  transition: all 0.3s;
}

.action-button:hover {
  transform: translateY(-2px);
  box-shadow: 0 4px 8px rgba(0, 0, 0, 0.2);
}

.dialog-footer {
  display: flex;
  justify-content: flex-end;
}
</style>
